<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>超时和网络异常</title>
    <style>
      #result {
        width: 200px;
        height: 100px;
        border: solid 1px purple;
      }
    </style>
  </head>
  <body>
    <button>点击发送请求</button>
    <div id="result"></div>

    <script>
      const btn = document.getElementsByTagName("button")[0];
      const result = document.querySelector("#result");

      btn.addEventListener("click", function () {
        const xhr = new XMLHttpRequest();
        //1.创建对象

        xhr.timeout = 2000;
        //设置2s的超时设置
        xhr.ontimeout = function () {
          alert("网络超时");
        };
        //设置超时的回调函数

        xhr.onerror = function () {
          alert("网络出了问题！");
        };
        //网络异常的回调

        xhr.open("GET", "http://127.0.0.1:7000/delay");
        //2.初始化请求类型，并写路径

        xhr.send();
        //3.发送请求

        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              result.innerHTML = xhr.response;
            }
          }
        };
        //对返回的进行处理
      });
    </script>
  </body>
</html>
